package com.example.springboottools.utils;

import cn.hutool.core.date.StopWatch;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static cn.hutool.core.io.IoUtil.close;
import static org.springframework.util.FileCopyUtils.BUFFER_SIZE;

public class ZipUtils {
    public static void main(String[] args)  {
        List<ByteArrayOutputStream> byteArrayOutputStreamList=new ArrayList<>();
        try {
            ByteArrayOutputStream aByte = PoiExcelUtils.getByte("D:\\staples\\日常记录\\工作记录\\2024\\03\\商品新增上架\\接口开发\\模板\\测试数据\\vendor_create_product-spicel.xls");
            ByteArrayOutputStream aByte1 = PoiExcelUtils.getByte("D:\\staples\\日常记录\\工作记录\\2024\\03\\商品新增上架\\接口开发\\模板\\测试数据\\vendor_create_product-spicel1.xls");
            byteArrayOutputStreamList.add(aByte);
            byteArrayOutputStreamList.add(aByte1);
            List<String> fileNameList=new ArrayList<>(Arrays.asList("aaa.xls","bbb.xls"));
            OutputStream out= new BufferedOutputStream(new FileOutputStream("D:\\staples\\日常记录\\工作记录\\2024\\03\\商品新增上架\\接口开发\\模板\\测试数据\\test.zip"));
            toZipByte(byteArrayOutputStreamList,fileNameList,out);
            out.flush();
            out.close();
        }catch (Exception e){

        }finally {
            byteArrayOutputStreamList.clear();
        }

    }
    public static void toZipByte(List<ByteArrayOutputStream> byteArrayOutputStreamList, List<String> fileNameList, OutputStream out) throws RuntimeException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("toZip-2");
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            for (int i = 0; i < fileNameList.size(); i++) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(fileNameList.get(i)));
                int len;
                ByteInputStream in = new ByteInputStream(byteArrayOutputStreamList.get(i).toByteArray(), byteArrayOutputStreamList.get(i).size());
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }

        } catch (Exception e) {
            throw new RuntimeException("压缩zip出错");
        } finally {
            close(zos);
        }
        stopWatch.stop();
    }
}
